
package com.sky.service.user.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.JwtClaimsConstant;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.user.UserMapper;
import com.sky.properties.JwtProperties;
import com.sky.properties.WeChatProperties;
import com.sky.service.user.LoginService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;

@Slf4j
@Service
public class LoginServiceImpl implements LoginService {

    //微信服务接口地址
    public static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";

    @Autowired
    private WeChatProperties weChatProperties;

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private JwtProperties jwtProperties;    //配置属性


    /**
     * 用户登录
     *
     * @param userLoginDTO
     */
    @Override
    public UserLoginVO login(UserLoginDTO userLoginDTO) {
        // 向微信平台发送appid、appsecret、code、authentication，获取session_key和openId
        HashMap<String , String> map = new HashMap<>();
        map.put("appid", weChatProperties.getAppid());
        map.put("secret", weChatProperties.getSecret());
        map.put("js_code", userLoginDTO.getCode());
        map.put("grant_type", "authorization_code");

        String json = HttpClientUtil.doGet(WX_LOGIN, map);

        JSONObject jsonObject = JSON.parseObject(json);

        String openId = jsonObject.getString("openid");

        // 获取到后将openId封装带authentication中，返回给小程序
        if (openId == null ){
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        User user = userMapper.selectByOpenId(openId);
        if (user == null ){
            // 不存在时则注册用户
            user = User.builder()
                    .openId(openId)
                    .createTime(LocalDateTime.now())
                    .build();
            userMapper.register(user);

        }

        // 小程序后续请求需要携带令牌信息，除了登录和查看状态
        HashMap<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID, user.getId());
        String authentication = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);
        UserLoginVO userLoginVO = UserLoginVO.builder()
                .id(user.getId())
                .openId(user.getOpenId())
                .token(authentication)
                .build();
        log.info(authentication);
        return userLoginVO;
    }
}
